import { getAllArea } from '@/services/common';
import { message } from 'antd';
import { find, memoize } from 'lodash';
import { useEffect, useMemo, useState } from 'react';
import { useFetch } from './useFetch';
function addressRecognition(data, val) {
  if (val) {
    try {
      const result = window.AddressParse.parse(val.replace(/\s+/g, ''))[0];
      let provinceId, cityId, areaId;
      const resp = {
        name: result.name,
        mobPhone: result.mobile,
        telPhone: result.phone,
        address: result.details.length > 120 ? result.details.slice(0, 120) : result.details,
      };
      if (result.province) {
        resp.proObj = find(data, ['name', result.province.replace('省', '')]);
        resp.provinceId = resp.proObj.id;
        resp.cityOptions = resp.proObj.childs;
      }
      if (result.city) {
        resp.cityObj = find(resp.proObj.childs, ['name', result.city]);
        resp.cityId = resp.cityObj.id;
        resp.areaOptions = resp.cityObj.childs;
      }

      if (result.area) {
        resp.areaObj = find(resp.cityObj.childs, ['name', result.area]);
        resp.areaId = resp.areaObj.id;
      }
      resp.area = resp.provinceId ? [resp.provinceId, resp.cityId, resp.areaId] : undefined;
      return resp;
    } catch (error) {
      console.log(error);
      message.error('地址识别失败');
    }
  } else {
    message.warning('请输入识别内容！');
  }
}

const getAllAreaMemo = memoize(getAllArea, (params) => JSON.stringify(params));

export function useAddress({ form, resetKey, provinceKey, cityKey, areaKey, addressKey, userKey, phoneKey, address='', onRecognize }) {
  const { data, fetch, loading } = useFetch(getAllAreaMemo, {}, true);
  const [cityOption, setCityOption] = useState([]);
  const [areaOption, setAreaOption] = useState([]);
  // const { updateConfig } = useAddressFieldsConfig();
  const [currentItem, setCurrentItem] = useState({ province: {}, city: {}, area: {}, address: '' })

  const [inputValue, setInputValue] = useState('');
  
  useEffect(() => {
    fetch().then(res => {
      if (address) {
        initData(address, res?.data);
      }
    })
  }, []);

  useEffect(()=>{
    !!resetKey && setInputValue('');
  }, [resetKey])

  const resolveData = useMemo(() => {
    if (data?.success && data?.data?.length) {
      return data.data;
    }
    return data;
  }, [data]);

  const baseProps = {
    fieldNames: {
      label: 'name',
      value: 'id',
    },
  };

  function initData(val, data) {
    const res = addressRecognition(data || resolveData, val);

    if (!res) {
      return;
    }
    
    resetForm(res)
  }

  function resetForm(res) {
    const { 
      name,
      mobPhone,
      telPhone,
      address,
      provinceId,
      cityId,
      areaId,
      cityOptions,
      areaOptions
    } = res;
    if (cityOptions) {
      setCityOption(cityOptions);
    }
    if (areaOptions) {
      setAreaOption(areaOptions);
    }
    form.setFieldValue(userKey, name);
    form.setFieldValue(phoneKey, mobPhone || telPhone);
    form.setFieldValue(provinceKey, provinceId);
    form.setFieldValue(cityKey, cityId);
    form.setFieldValue(areaKey, areaId);
    form.setFieldValue(addressKey, address);
    setCurrentItem({
      province: res.proObj || {},
      city: res.cityObj || {},
      area: res.areaObj || {},
      address: address
    })
    onRecognize?.(res);
  }

  function resizeFormByServe(initForm) {
    const provinceOptions = resolveData;
    const cityOptions = resolveData.find(el => initForm.province === el.name)?.childs || [];
    const areaOptions = cityOptions.find(el => initForm.city === el.name)?.childs || [];

    const provinceId = provinceOptions.find(el => el.name === initForm.province)?.id
    const cityId = cityOptions.find(el => el.name === initForm.city)?.id
    const areaId = areaOptions.find(el => el.name === initForm.area)?.id

    if (cityOptions) {
      setCityOption(cityOptions);
    }
    if (areaOptions) {
      setAreaOption(areaOptions);
    }

    form.setFieldValue(provinceKey, provinceId);
    form.setFieldValue(cityKey, cityId);
    form.setFieldValue(areaKey, areaId);
  }

  function withProvinceProps(props) {
    return {
      ...baseProps,
      options: resolveData,
      placeholder: '请选择省',
      ...props,
      onChange(value, option) {
        setCityOption(option?.childs || []);
        setAreaOption([]);
        form.resetFields([cityKey, areaKey]);
        form.setFieldValue(cityKey, null);
        form.setFieldValue(areaKey, null);
        setCurrentItem({
          province: option,
          city: {},
          area: {},
          address: ''
        })
        return props?.onChange?.(value, option);
      },
    };
  }

  function withCityProps(props) {
    return {
      ...baseProps,
      options: cityOption,
      placeholder: '请选择市',
      ...props,
      onChange: (value, option) => {
        setAreaOption(option?.childs || []);
        form.resetFields([areaKey]);
        form.setFieldValue(areaKey, null);

        setCurrentItem({
          ...currentItem,
          city: option,
          area: {},
        })
        return props?.onChange?.(value, option);
      },
    };
  }

  function withAreaProps(props) {
    return {
      ...baseProps,
      options: areaOption,
      placeholder: '请选择区',
      ...props,
      onChange (value, option) {
        setCurrentItem({
          ...currentItem,
          area: option,
        })

        return props?.onChange?.(value, option);
      }
    };
  }

  function withAddressRecognitionProps(props) {
    return {
      placeholder: '地址识别粘贴地址回车后自动识别，例如：张三，15712345678，广东省 广州市 天河区 平安大厦',
      ...props,
      value: inputValue,
      onBlur: (e) => {
        if (!e.target.value) {
          return;
        }
        initData(e.target.value);
      },
      onPressEnter: (e) => {
        if (!e.target.value) {
          return;
        }
        initData(e.target.value);
      },
      onChange: e=>setInputValue(e.target.value)
    };
  }

  return {
    data: resolveData,
    loading,
    currentAreaItem: currentItem,

    withProvinceProps,
    withCityProps,
    withAreaProps,
    withAddressRecognitionProps,

    resizeFormByServe,
  };
}
